<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isNew ? '新建用户' : '修改用户'"
    width="700px"
    :before-close="close"
    :close-on-click-modal="false"
  >
    <el-scrollbar max-height="60vh" v-loading="loading">
      <el-form ref="formRef" :model="formData" label-width="110" :rules="rules">
        <el-form-item label="账号：" prop="userName">
          <el-input v-model="formData.userName" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="用户名：" prop="name">
          <el-input v-model="formData.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="单位：" prop="unitIdArray">
          <UnitCascader v-model="formData.unitIdArray" />
        </el-form-item>
        <el-form-item label="手机号：" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="激活状态：" prop="state">
          <el-switch
            v-model="formData.state"
            active-text="激活"
            inactive-text="停用"
            :active-value="0"
            :inactive-value="1"
          />
        </el-form-item>
        <el-form-item label="超级管理员：" prop="isAdmin">
          <el-switch
            v-model="formData.isAdmin"
            active-text="是"
            inactive-text="否"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <template v-if="formData.isAdmin === 0">
          <el-form-item label="角色权限：" prop="power">
            <RolePermissionInputTable
              ref="rolePermissionInputTable"
              power-type="2"
              :permission="addPermission"
              :user-id="formData.id"
            />
          </el-form-item>
        </template>
      </el-form>
    </el-scrollbar>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="submit" :loading="loading">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { reactive, ref, useTemplateRef } from 'vue'
import { FormInstance, FormRules } from 'element-plus'
import {
  queryRoleDataByUserId,
  saveOrUpdateUserInfo,
} from '@/api/sys/userManage'
import RolePermissionInputTable from '@/components/dataPermission/RolePermissionInputTable.vue'
import UnitCascader from '@/components/unit/UnitCascader.vue'
import { Message } from '@/hooks/message'

const addPermission = 'user:add'

const formRef = useTemplateRef<FormInstance>('formRef')
const rolePermissionInputTable = useTemplateRef<
  InstanceType<typeof RolePermissionInputTable>
>('rolePermissionInputTable')
const emit = defineEmits(['update'])

const dialogVisible = ref(false)
const isNew = ref(true)
const loading = ref(false)

const formData = reactive({
  id: undefined,
  userName: '',
  name: '',
  unitIdArray: [],
  phone: '',
  state: 1,
  isAdmin: 0,
  power: undefined,
  sysUserRoles: [],
})

const rules = reactive<FormRules<typeof formData>>({
  userName: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' },
    {
      pattern: /^[A-Za-z0-9]+$/,
      message: '不允许使用特殊字符',
      trigger: 'blur',
    },
  ],
  name: { required: true, message: '请输入用户名', trigger: 'blur' },
  unitIdArray: { required: true, message: '请选择组织单位', trigger: 'change' },
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    {
      pattern: /^1[3456789]\d{9}$/,
      message: '请输入正确的手机号',
      trigger: 'blur',
    },
  ],
  state: { required: true, message: '请选择激活状态', trigger: 'change' },
  isAdmin: { required: true, message: '请选择是否管理员', trigger: 'change' },
  power: { validator: checkRoleTable, trigger: 'noTrigger', required: true },
})

defineExpose({ show })

function show(row?: any) {
  dialogVisible.value = true
  if (row) {
    formData.id = row.id
    formData.userName = row.userName
    formData.name = row.name
    formData.unitIdArray = [row.unitId, row.departmentId]
    formData.phone = row.phone
    formData.state = row.state
    formData.isAdmin = row.isAdmin
    isNew.value = false
    if (formData.isAdmin === 0) {
      getUserRole(formData.id)
    }
  }
}

function close() {
  dialogVisible.value = false
  isNew.value = true
  loading.value = false
  formRef.value.resetFields()
  Object.assign(formData, {
    id: undefined,
    userName: '',
    name: '',
    unitIdArray: [],
    phone: '',
    state: 1,
    isAdmin: 0,
    power: undefined,
    sysUserRoles: [],
  })
  rolePermissionInputTable.value?.clearTableData()
}

function checkRoleTable(rule: any, value: any, callback: any) {
  rolePermissionInputTable.value.checkTableData(rule, value, callback)
}

async function getUserRole(id: number) {
  const { data } = await queryRoleDataByUserId(id)
  if (data.status === 200) {
    await rolePermissionInputTable.value.setTableData(data.data)
  }
}

async function submit() {
  const bool = await formRef.value.validate()
  if (!bool) {
    return
  }
  loading.value = true
  if (formData.isAdmin === 0) {
    formData.sysUserRoles = rolePermissionInputTable.value.getTableData()
  } else {
    formData.sysUserRoles = []
  }
  const postData = {
    ...formData,
    unitId: formData.unitIdArray[0],
    departmentId: formData.unitIdArray[1],
  }
  const { data } = await saveOrUpdateUserInfo(postData)
  if (data.status === 200) {
    Message({
      message: data.message,
      type: 'success',
    })
  }
  loading.value = false
  emit('update')
  close()
}
</script>
<style scoped lang="scss"></style>
